﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CubicFWNet.Application.SystemManager;
using CubicFWNet.Common;
using CubicFWNet.Data.Models;
using CubicFWNet.Data.ViewModal;
using PagedList;

namespace CubicFWNet.Mvc.Controllers
{
    public class WorksheetController : ControllerBase
    {
        private WorksheetApp _worksheetApp;
        private OrderProductApp _orderProductApp;
        private TechnologyApp _technologyApp;
        private OperateRecordApp _operateRecordApp;
        private ExamineApp _examineApp;
        private OrderApp _orderApp;
        private CreateNewNumberApp _createNewNumberApp;
        private CustomerApp _customerApp;
        private PurchaseApp _purchaseApp;

        public WorksheetController()
        {
            _worksheetApp = new WorksheetApp();
            _orderProductApp = new OrderProductApp();
            _technologyApp = new TechnologyApp();
            _operateRecordApp = new OperateRecordApp();
            _examineApp = new ExamineApp();
            _orderApp = new OrderApp();
            _createNewNumberApp = new CreateNewNumberApp();
            _customerApp = new CustomerApp();
            _purchaseApp = new PurchaseApp();
        }

        // GET: Worksheet
        public ActionResult Index()
        {
            return View();
        }



        public ActionResult Check(int page = 1, string productName = "", string productNum = "", string beginTime = "", string endTime = "")
        {
            ViewBag.ProductName = productName.Trim();
            ViewBag.ProductNum = productNum.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }
            IPagedList<ProductTechnologyView> tecjList = _worksheetApp.GetList(-1, productName.Trim(), productNum.Trim(), _beginTime, _endTime).ToPagedList(page, 10);
            return View(tecjList);
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string WorksheetChangeType(Guid equipmentType, int techType)
        {
            TechType techTypeObj = _technologyApp.GetSingleTechType(equipmentType, techType);
            return techTypeObj.MinuteNum.ToJson();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tId"></param>
        /// <param name="type">0:正常生产  1：补单生产</param>
        /// <returns></returns>
        public ActionResult CheckInfo(Guid tId, int type)
        {
            Worksheet w = _worksheetApp.GetSingleWorksheet(tId);
            Product p = _technologyApp.GetSingleProduct(w.ProductId);
            w.Type = type;

            Order order = null;
            OrderProduct op = null;
            Technology t = null;
            TechType techType = null;
            List<TechType> levelList = null;
            ProductTechnologyView firstMaterial = null;
            List<ProductTechnologyView> technologyItem = null;
            if (w.OtherId != null)
            {
                order = _orderApp.GetInfo(w.OtherId.Value);
            }
            op = _orderProductApp.GetSingleOrderProductById(tId);
            if (op == null && w.ParentId != null)
            {
                op = _orderProductApp.GetSingleOrderProductById(w.ParentId.Value);
            }
            if (op != null)
            {
                if (op.PrimaryID != null)
                {
                    t = _technologyApp.GetSingleTechnologyById(op.PrimaryID.Value);
                }
                else
                {
                    t = _technologyApp.GetSingleTechnologyById(op.Id);
                }
                if (t != null)
                {
                    techType = _technologyApp.GetSingleTechType(t.EquipmentType, t.TechType);
                    firstMaterial = _technologyApp.GetFirstItem(t.Id);//主料
                    technologyItem = _technologyApp.GetTechnologyItems(t.Id);//辅料
                    levelList = _technologyApp.GetListTechType(t.EquipmentType, "").ToList();
                }
            }
            IEnumerable<Equipment> listEquipments = _technologyApp.GetListEquipment("");//设备
            if (type == 0)
            {
                if (op != null)
                {
                    decimal amount = w.StandardAmount;
                    Worksheet temp = _worksheetApp.GetSingleWorksheet(tId);
                    //分批生产
                    if (temp.Type == 2 && temp.ParentId != null)
                    {
                        amount += temp.WorkAmount;
                        w.WorkAmount = amount;
                    }
                    else
                    {
                        IEnumerable<Worksheet> subList = _worksheetApp.GetSubListTotal(tId);
                        if (subList != null)
                        {
                            foreach (var item in subList)
                            {
                                amount += item.WorkAmount;
                            }
                        }
                        w.WorkAmount = op.Amount - amount;
                    }
                }
                else
                {
                    w.WorkAmount = 0;
                }
            }


            if (type == 1)
            {
                decimal amount = w.StandardAmount;
                IEnumerable<Worksheet> subList = _worksheetApp.GetSubList(tId);
                if (subList != null)
                {
                    foreach (var item in subList)
                    {
                        //可能没有质检
                        if (item.StandardAmount == 0)
                        {
                            amount += item.WorkAmount;
                        }
                    }
                }
                w.WorkAmount = w.WorkAmount - amount;
            }

            ViewBag.LevelList = levelList;//类别集合
            ViewBag.TechnologyItemList = technologyItem;
            ViewBag.ProductTechnologyView = firstMaterial;
            ViewBag.ListEquipments = listEquipments;
            ViewBag.TechType = techType;
            ViewBag.Technology = t;
            ViewBag.OrderProduct = op;
            ViewBag.Order = order;
            ViewBag.Product = p;
            string operationName = operatorModel.FamilyName;

            string newNumber = "";
            if (string.IsNullOrEmpty(w.Number))
            {
                #region 生成订单号

                string shortName = operatorModel.FamilyName;
                string shortTime = GenerateId.GenerateyyyyMm();
                //int lastWorksheet = _createNewNumberApp.GetLastWorksheetCount(shortName + "-" + shortTime, p.WorkType);
                int lastWorksheet = _createNewNumberApp.GetLastWorksheetCount(shortName + "-" + shortTime);
                int lastNum = lastWorksheet + 1;
                newNumber = shortName + "-" + GenerateId.GenerateOrderNumberBack() + "-" +
                            lastNum.ToString().PadLeft(3, '0'); //生成采购编号

                #endregion
            }
            else
            {
                newNumber = w.Number;
            }

            ViewBag.WorksheetNumber = newNumber;//生成加工编号
            ViewBag.OperationName = operationName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间

            return View(w);
        }

        /// <summary>
        /// 还原重新分配
        /// </summary>
        /// <param name="wid"></param>
        /// <returns></returns>
        public JsonResult WorkRestore(Guid wid)
        {
            Worksheet w = _worksheetApp.GetSingleWorksheet(wid);
            OrderProduct op = null;
            if (w == null)
            {
                return Json(-1);
            }
            if (w.ParentId != null)
            {
                op = _orderProductApp.GetSingleOrderProductById(w.ParentId.Value);
            }
            else
            {
                op = _orderProductApp.GetSingleOrderProductById(w.Id);
            }
            if (op == null)
            {
                return Json(-1);
            }
            //获取需要还原的数量
            //decimal realAmount = op.Amount;

            //op.Amount = realAmount;
            op.WorksheetId = null;
            op.Progress = 0;
            op.Type = 0;
            op.Status = 0;
            _orderProductApp.Update(op);

            var pur = _purchaseApp.GetSingle(op.PurchaseId.Value);
            if (pur != null)
            {
                pur.Status = 1;
                _purchaseApp.Update(pur);
            }

            if (w.Type == 2 && w.ParentId != null)
            {
                Worksheet temp = _worksheetApp.GetSingleWorksheet(w.ParentId.Value);
                IEnumerable<Worksheet> subList = _worksheetApp.GetSubList(temp.Id);
                foreach (var item in subList)
                {
                    _technologyApp.DeleteRelation(item.Id, item.OtherId.Value, "Worksheet-Order");
                }
                _technologyApp.DeleteRelation(temp.Id, temp.OtherId.Value, "Worksheet-Order");

                _worksheetApp.Delete(temp.Id);
                _worksheetApp.DeleteByParentId(temp.Id);
            }
            if (w.Type == 0)
            {
                IEnumerable<Worksheet> subList = _worksheetApp.GetSubList(w.Id);
                foreach (var item in subList)
                {
                    _technologyApp.DeleteRelation(item.Id, item.OtherId.Value, "Worksheet-Order");
                }
                _technologyApp.DeleteRelation(w.Id, w.OtherId.Value, "Worksheet-Order");

                _worksheetApp.Delete(w.Id);
                _worksheetApp.DeleteByParentId(w.Id);
            }
            return Json(0);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="worksheet"></param>
        /// <param name="productAccount">订货数量</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public string AddCheck(Worksheet worksheet, decimal productAccount)
        {
            DateTime nowTime = DateTime.Now;

            //填写工单
            if (worksheet.Type == 0)
            {
                //说明是分加工的
                if (worksheet.WorkAmount < productAccount)
                {
                    Guid orgiGuidId = worksheet.Id; //初始Id
                    Worksheet w = _worksheetApp.GetSingleWorksheet(worksheet.Id);
                    w.Number = "";
                    w.WorkAmount = w.WorkAmount + worksheet.WorkAmount;
                    _worksheetApp.Update(w); //原加工单不动，只修改加工数量

                    //修改OrderProduct工作进度
                    OrderProduct op = _orderProductApp.GetSingleOrderProductById(worksheet.Id);
                    if (op == null && w.ParentId != null)
                    {
                        op = _orderProductApp.GetSingleOrderProductById(w.ParentId.Value);
                    }
                    if (op != null)
                    {
                        op.Progress = 9;
                        _orderProductApp.Update(op);
                    }

                    //已生产的数量则另生个个加工单
                    Guid newGuidId = Guid.NewGuid();
                    worksheet.Id = newGuidId;
                    worksheet.Status = 1;
                    worksheet.Type = 2;
                    worksheet.ParentId = orgiGuidId;
                    worksheet.CreatorId = operatorModel.UserId;
                    worksheet.CreatorName = operatorModel.FamilyName;
                    worksheet.CreateTime = nowTime;
                    _worksheetApp.Add(worksheet);

                    Relation re1 = new Relation();
                    re1.Id = Guid.NewGuid();
                    re1.TypeId = "Worksheet-Order";
                    re1.FirstId = newGuidId;
                    re1.SecondId = worksheet.OtherId;
                    _technologyApp.InsertRelation(re1);

                    //插入给下一个工作人员添加人工记录（加工单）
                    OperateRecord o2 = new OperateRecord();
                    o2.Id = Guid.NewGuid();
                    o2.ItemId = newGuidId;//
                    o2.TypeId = 11;
                    o2.StartTime = w.ApplyTime;
                    o2.EndTime = nowTime;
                    o2.CreatorId = operatorModel.UserId;
                    _operateRecordApp.AddOperateRecord(o2);

                }
                else
                {
                    worksheet.Status = 1;
                    worksheet.ParentId = null;
                    worksheet.CreatorId = operatorModel.UserId;
                    worksheet.CreatorName = operatorModel.FamilyName;
                    worksheet.CreateTime = nowTime;
                    _worksheetApp.Update(worksheet);

                    //修改OrderProduct工作进度
                    OrderProduct op = _orderProductApp.GetSingleOrderProductById(worksheet.Id);
                    if (op == null && worksheet.ParentId != null)
                    {
                        op = _orderProductApp.GetSingleOrderProductById(worksheet.ParentId.Value);
                    }
                    if (op != null)
                    {
                        op.Progress = 9;
                        _orderProductApp.Update(op);
                    }

                    OperateRecord o = new OperateRecord();
                    o.ItemId = worksheet.Id;
                    o.TypeId = 11;
                    o.EndTime = nowTime;
                    o.CreatorId = operatorModel.UserId;
                    o.CreatorName = operatorModel.FamilyName;
                    _operateRecordApp.UpdateOperateRecord(o);//修改本操作人员工作记录日志
                }
            }

            //接着加工（新建工单）
            if (worksheet.Type == 1)
            {
                Worksheet w = _worksheetApp.GetSingleWorksheet(worksheet.Id);

                //Worksheet ws = new Worksheet();
                Guid newwsId = Guid.NewGuid();
                worksheet.ParentId = worksheet.Id;
                worksheet.Id = newwsId;
                worksheet.Status = 1;
                worksheet.Type = 1;
                worksheet.StandardAmount = 0;
                worksheet.ApplyTime = nowTime;
                worksheet.ProductId = worksheet.ProductId;
                worksheet.ProductName = worksheet.ProductName;
                worksheet.OtherId = worksheet.OtherId;
                worksheet.CreatorId = operatorModel.UserId;
                worksheet.CreatorName = operatorModel.FamilyName;
                worksheet.CreateTime = nowTime;
                _worksheetApp.Add(worksheet);


                Relation re1 = new Relation();
                re1.Id = Guid.NewGuid();
                re1.TypeId = "Worksheet-Order";
                re1.FirstId = newwsId;
                re1.SecondId = worksheet.OtherId;
                _technologyApp.InsertRelation(re1);

                //操作记录
                OperateRecord o2 = new OperateRecord();
                o2.Id = Guid.NewGuid();
                o2.ItemId = newwsId;
                o2.TypeId = 11;
                o2.StartTime = w.ApplyTime;
                o2.EndTime = nowTime;
                o2.CreatorId = operatorModel.UserId;
                o2.CreatorName = operatorModel.FamilyName;
                _operateRecordApp.AddOperateRecord(o2);
            }

            Examine e = new Examine();//插入质检表
            Guid newId = Guid.NewGuid();
            e.Id = newId;
            e.Type = 2;
            e.ItemId = worksheet.Id;
            e.ApplyTime = nowTime;
            e.CreatorId = null;
            e.CreateTime = null;
            e.Status = -1;
            e.ApplyId = operatorModel.UserId;
            _examineApp.Add(e);

            //插入给下一个工作人员添加人工记录（原料成本核算）
            OperateRecord o1 = new OperateRecord();
            o1.Id = Guid.NewGuid();
            o1.ItemId = newId;//工单id
            o1.TypeId = 15;
            o1.StartTime = nowTime;
            o1.EndTime = null;
            o1.CreatorId = null;
            _operateRecordApp.AddOperateRecord(o1);


            //OrderProduct op = _orderProductApp.GetSingleOrderProductById(worksheet.Id);//根据工艺订单id查找关系表对应的OrderId
            //if (null != op)
            //{
            //    int count = _orderProductApp.GetCheckTOrderProductByOrderId(op.OrderId.Value);//如果订单旗下所有工艺都审核完毕才修改订单状态
            //    if (count == 0)
            //    {
            //        _operateRecordApp.UpdateOrderStateById(op.OrderId.Value, 9);//更改订单Status=9
            //    }
            //}

            return Result.ToJson();
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdateCheckWorksheet(Worksheet worksheet)
        {
            Worksheet w = _worksheetApp.GetSingleWorksheet(worksheet.Id);
            if (w != null)
            {
                w.Data = worksheet.Data;
                w.LingData = worksheet.LingData;
                w.TuiData = worksheet.TuiData;
                w.ActualMaterial = worksheet.ActualMaterial;
                w.Memo = worksheet.Memo;
                w.ActualHours = worksheet.ActualHours;
                w.Status = 3;
                _worksheetApp.Update(w);
            }

            return Result.ToJson();
        }

        public ActionResult Query(int page = 1, string productName = "", string productNum = "", string beginTime = "", string endTime = "")
        {
            ViewBag.ProductName = productName.Trim();
            ViewBag.ProductNum = productNum.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }
            IPagedList<ProductTechnologyView> tecjList = _worksheetApp.GetListSortByType(4, productName.Trim(), productNum.Trim(), _beginTime, _endTime).ToPagedList(page, 10);
            return View(tecjList);
        }

        public ActionResult OksResult(int page = 1, string productName = "", string productNum = "", string beginTime = "", string endTime = "")
        {
            ViewBag.ProductName = productName.Trim();
            ViewBag.ProductNum = productNum.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }
            IPagedList<ProductTechnologyView> tecjList = _worksheetApp.GetList(5, productName.Trim(), productNum.Trim(), _beginTime, _endTime).ToPagedList(page, 10);
            return View(tecjList);
        }

        public ActionResult QueryInfo(Guid tId, int type)
        {
            Worksheet w = _worksheetApp.GetSingleWorksheet(tId);
            Product p = _technologyApp.GetSingleProduct(w.ProductId);
            Technology t = null;
            OrderProduct op = null;
            Order order = null;
            ProductTechnologyView firstMaterial = null;
            List<ProductTechnologyView> technologyItem = null;
            Equipment equipments = null;
            TechType techType = null;
            if (w.OtherId != null)
            {
                order = _orderApp.GetInfo(w.OtherId.Value);
            }
            if (w.EquipmentType != null)
            {
                equipments = _technologyApp.GetSingleEquipment(w.EquipmentType.Value);//设备
                techType = _technologyApp.GetSingleTechType(equipments.Id, w.TechType);
            }


            if (w.TechnologyId != null)
            {
                t = _technologyApp.GetSingleTechnology(w.TechnologyId.Value);
                firstMaterial = _technologyApp.GetFirstItem(t.Id);//主料
                technologyItem = _technologyApp.GetTechnologyItems(t.Id);//辅料
            }
            else
            {
                op = _orderProductApp.GetSingleOrderProductById(tId);//查找第一次
                if (op == null && w.ParentId != null)
                {
                    op = _orderProductApp.GetSingleOrderProductById(w.ParentId.Value);//查找第二次
                    if (op == null)
                    {
                        Worksheet tempw = _worksheetApp.GetSingleWorksheet(w.ParentId.Value);
                        if (tempw != null && tempw.ParentId != null && tempw.Type == 2)
                        {
                            op = _orderProductApp.GetSingleOrderProductById(tempw.ParentId.Value);//查找第三次
                        }
                    }
                }
                if (op != null)
                {
                    t = _technologyApp.GetSingleTechnologyById(op.Id);
                    firstMaterial = _technologyApp.GetFirstItem(t.Id);//主料
                    technologyItem = _technologyApp.GetTechnologyItems(t.Id);//辅料
                }
            }

            ViewBag.Order = order;
            ViewBag.TechnologyItemList = technologyItem;
            ViewBag.ProductTechnologyView = firstMaterial;
            ViewBag.Equipments = equipments;
            ViewBag.TechType = techType;
            ViewBag.Product = p;
            ViewBag.Technology = t;
            ViewBag.OrderProduct = op;
            return View(w);
        }

        /// <summary>
        /// 添加新加工单（原有工单接着生产）
        /// </summary>
        /// <param name="tId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult AddNewWorksheet(Guid tId, int type)
        {
            Worksheet w = _worksheetApp.GetSingleWorksheet(tId);
            w.Type = type;
            w.Status = -1;
            OrderProduct op = _orderProductApp.GetSingleOrderProductById(tId);
            Technology t = _technologyApp.GetSingleTechnologyById(op.Id);
            Product p = _technologyApp.GetSingleProduct(w.ProductId);
            TechType techType = _technologyApp.GetSingleTechType(t.EquipmentType, t.TechType);

            ProductTechnologyView firstMaterial = _technologyApp.GetFirstItem(t.Id);//主料
            List<ProductTechnologyView> technologyItem = _technologyApp.GetTechnologyItems(t.Id);//辅料
            IEnumerable<Equipment> listEquipments = _technologyApp.GetListEquipment("");//设备

            //w.ExpectedMaterial = t.GiveW * t.GiveH;


            ViewBag.TechnologyItemList = technologyItem;
            ViewBag.ProductTechnologyView = firstMaterial;
            ViewBag.ListEquipments = listEquipments;
            ViewBag.TechType = techType;
            ViewBag.Technology = t;
            ViewBag.OrderProduct = op;
            ViewBag.Product = p;
            string shortName = operatorModel.FamilyName;//OperatorProvider.Provider.GetCurrent()
            string operationName = operatorModel.FamilyName;
            ViewBag.WorksheetNumber = shortName + "-" + GenerateId.GenerateOrderNumber();//生成加工编号
            ViewBag.OperationName = operationName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间
            return View(w);
        }


        /// <summary>
        /// 判断该生产单是否可以再补单
        /// </summary>
        /// <param name="tId"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public string VerifyWorksheet(Guid tId)
        {
            Result.Status = "2";
            Worksheet w = _worksheetApp.GetSingleWorksheet(tId);
            if (w != null)
            {
                decimal amount = w.StandardAmount;
                IEnumerable<Worksheet> subList = _worksheetApp.GetSubList(tId);
                if (subList != null)
                {
                    foreach (var item in subList)
                    {
                        //可能没有质检
                        if (item.StandardAmount == 0)
                        {
                            amount += item.WorkAmount;
                        }
                    }
                }
                if (w.WorkAmount > amount)//申请数量>总补单数量和本身合格数量
                {
                    Result.Status = "1";
                }
            }
            return Result.ToJson();
        }

        /// <summary>
        /// 切卷模版
        /// </summary>
        /// <param name="tId"></param>
        /// <param name="sl"></param>
        /// <param name="sw"></param>
        /// <param name="ch"></param>
        /// <param name="cv"></param>
        /// <param name="tMemo"></param>
        /// <param name="count">本次生产数量</param>
        /// <param name="pac">订货数量</param>
        /// <param name="eqName">设备</param>
        /// <returns></returns>
        public ActionResult PrintWorksheetQj(Guid tId, string sl, string sw, decimal ch, decimal cv, string tMemo, decimal count, decimal pac, string eqName)
        {
            Worksheet w = _worksheetApp.GetSingleWorksheet(tId);
            Product p = _technologyApp.GetSingleProduct(w.ProductId);

            Technology t = null;
            OrderProduct op = null;
            Order order = null;
            ProductTechnologyView firstMaterial = null;
            List<ProductTechnologyView> technologyItem = null;
            Equipment equipments = null;
            TechType techType = null;
            string dgpeople = "";
            if (w.OtherId != null)
            {
                order = _orderApp.GetInfo(w.OtherId.Value);
                if (order != null && order.UserId != null)
                {
                    User xiaoshou = _customerApp.GetUser(order.UserId.Value);
                    dgpeople = xiaoshou.RealName;
                }
            }
            if (w.EquipmentType != null)
            {
                equipments = _technologyApp.GetSingleEquipment(w.EquipmentType.Value);//设备
                techType = _technologyApp.GetSingleTechType(equipments.Id, w.TechType);
            }

            if (w.TechnologyId != null)
            {
                t = _technologyApp.GetSingleTechnology(w.TechnologyId.Value);
                firstMaterial = _technologyApp.GetFirstItem(t.Id);//主料
                technologyItem = _technologyApp.GetTechnologyItems(t.Id);//辅料
            }
            else
            {
                op = _orderProductApp.GetSingleOrderProductById(tId);//查找第一次
                if (op == null && w.ParentId != null)
                {
                    op = _orderProductApp.GetSingleOrderProductById(w.ParentId.Value);//查找第二次
                    if (op == null)
                    {
                        Worksheet tempw = _worksheetApp.GetSingleWorksheet(w.ParentId.Value);
                        if (tempw != null && tempw.ParentId != null && tempw.Type == 2)
                        {
                            op = _orderProductApp.GetSingleOrderProductById(tempw.ParentId.Value);//查找第三次
                        }
                    }
                }
                if (op != null)
                {
                    if (op.PrimaryID != null)
                    {
                        t = _technologyApp.GetSingleTechnologyById(op.PrimaryID.Value);
                    }
                    else
                    {
                        t = _technologyApp.GetSingleTechnologyById(op.Id);
                    }
                    firstMaterial = _technologyApp.GetFirstItem(t.Id);//主料
                    technologyItem = _technologyApp.GetTechnologyItems(t.Id);//辅料
                }
            }

            if (op != null)
            {
                decimal amount = w.StandardAmount;
                IEnumerable<Worksheet> subList = _worksheetApp.GetSubListTotal(tId);
                if (subList != null)
                {
                    foreach (var item in subList)
                    {
                        amount += item.WorkAmount;
                    }
                }
                //w.WorkAmount = op.Amount - amount;
                //重新计算给定长宽
                /*decimal sizeWidth = p.SizeWidth.Value;
                decimal sizeLenth = p.SizeLenth.Value;
                decimal chorg = t.Ch == 0 ? 1 : t.Ch;
                decimal space = t.Space; //左右间距-mm
                decimal margin = t.Margin; //左右边距-mm
                decimal distance = t.Distance; //跳距-mm
                var giveW = (sizeWidth * chorg + (chorg - 1) * space + margin * 2 * chorg);//给定用料宽-mm  margin * 2 * ch
                var comH = w.WorkAmount / chorg;
                var giveH = (sizeLenth + distance) * comH / 1000;//给定用料长-m(米)*/
                t.GiveW = sw;
                t.GiveH = sl;

                #region  储存每次打印数据
                Worksheet wback = _worksheetApp.GetSingleWorksheet(tId);
                List<TechnologyItemView> itemList = new List<TechnologyItemView>();
                PrintDataView pdw = new PrintDataView();
                pdw.ProductId = p.Id;
                pdw.ProductName = p.Name;
                pdw.SizeWidth = sw;
                pdw.SizeLenth = sl;
                pdw.GiveW = 0;
                pdw.GiveH = 0;
                pdw.WorkAmount = w.WorkAmount;
                pdw.FirstMaterial = firstMaterial.ProductName;
                //pdw.Tolerance = p.Tolerance;
                //pdw.ToleranceMinus = p.ToleranceMinus;
                pdw.Cv = cv;
                pdw.Ch = 0;
                //pdw.Angel = p.Angel;
                //pdw.Color = p.Color;
                pdw.Distance = 0;
                pdw.WorkLenth = t.WorkLenth;
                pdw.Space = 0;
                pdw.Margin = 0;
                //pdw.PackRequire = p.PackRequire;
                pdw.TechnologMemo = tMemo;
                pdw.EquipmentName = eqName;
                pdw.Dgren = dgpeople;
                pdw.OperationName = operatorModel.FamilyName;
                //pdw.Pack = p.Pack;
                //pdw.PackAmount = p.PackAmount;//w.WorkAmount / (p.PackAmount == 0 ? 1 : p.PackAmount);
                foreach (var item in technologyItem)
                {
                    TechnologyItemView techItem = new TechnologyItemView();
                    techItem.ProductItemName = item.ProductName;
                    itemList.Add(techItem);
                }
                wback.PrintData = pdw.ToJson();
                _worksheetApp.Update(wback);
                #endregion
            }
            string newNumber = "";
            if (string.IsNullOrEmpty(w.Number))
            {
                #region 生成订单号

                string shortName = operatorModel.FamilyName;
                string shortTime = GenerateId.GenerateyyyyMm();
                //int lastWorksheet = _createNewNumberApp.GetLastWorksheetCount(shortName + "-" + shortTime, p.WorkType);
                int lastWorksheet = _createNewNumberApp.GetLastWorksheetCount(shortName + "-" + shortTime);
                /*int lastNum = 1;
                if (lastWorksheet != null && lastWorksheet.Number.Split('-').Length == 3 &&
                    Validate.IsIntByParse(lastWorksheet.Number.Split('-')[2]))
                {
                    int lastNum = Convert.ToInt32(lastWorksheet.Number.Split('-')[2]) + 1;
                }*/
                int lastNum = lastWorksheet + 1;
                newNumber = shortName + "-" + GenerateId.GenerateOrderNumberBack() + "-" +
                            lastNum.ToString().PadLeft(3, '0'); //生成采购编号

                #endregion
            }
            else
            {
                newNumber = w.Number;
            }


            w.Number = newNumber;
            w.CreateTime = DateTime.Now;
            w.WorkAmount = count;
            p.SizeWidth = sw;
            p.SizeLenth = sl;
            t.Ch = ch;
            t.Cv = cv;

            ViewBag.ProductAccount = pac;
            ViewBag.Order = order;
            ViewBag.TechnologyItemList = technologyItem;
            ViewBag.FirstMaterial = firstMaterial;
            ViewBag.Product = p;
            ViewBag.Technology = t;
            ViewBag.OrderProduct = op;
            return View(w);
        }

        /// <summary>
        /// 打印背面
        /// </summary>
        /// <param name="proName"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public ActionResult PrintWorksheetBack(string proName, string number)
        {
            ViewBag.ProName = proName;
            ViewBag.Number = number;
            return View();
        }
        /// <summary>
        /// 普通模版
        /// </summary>
        /// <param name="tId"></param>
        /// <param name="sl">长</param>
        /// <param name="sw">宽</param>
        /// <param name="ch">刀模数[左右]</param>
        /// <param name="cv">刀模数[排]</param>
        /// <param name="tMemo">注意事项与工艺</param>
        /// <param name="count">本次生产数量</param>
        /// <param name="pac">订货数量</param>
        /// <param name="eqName">eqName</param>
        /// <returns></returns>
        public ActionResult PrintWorksheet(Guid tId, string sl, string sw, decimal ch, decimal cv, string tMemo, decimal count, decimal pac, string eqName)
        {

            Worksheet w = _worksheetApp.GetSingleWorksheet(tId);
            Product p = _technologyApp.GetSingleProduct(w.ProductId);

            //if (p.WorkType == 2)
            //{
            //    return RedirectToAction("PrintWorksheetQj", new { tId = tId, sl = sl, sw = sw, ch = ch, cv = cv, tMemo = tMemo, count = count, pac = pac, eqName = eqName });
            //}
            Technology t = null;
            OrderProduct op = null;
            Order order = null;
            ProductTechnologyView firstMaterial = null;
            List<ProductTechnologyView> technologyItem = null;
            Equipment equipments = null;
            TechType techType = null;
            string dgpeople = "";//订购人
            if (w.OtherId != null)
            {
                order = _orderApp.GetInfo(w.OtherId.Value);
                if (order != null && order.UserId != null)
                {
                    User xiaoshou = _customerApp.GetUser(order.UserId.Value);
                    dgpeople = xiaoshou.RealName;
                }

            }
            /*if (w.EquipmentType != null)
            {
                equipments = _technologyApp.GetSingleEquipment(w.EquipmentType.Value);//设备
                techType = _technologyApp.GetSingleTechType(equipments.Id, w.TechType);
            }*/

            if (w.TechnologyId != null)
            {
                t = _technologyApp.GetSingleTechnology(w.TechnologyId.Value);
                firstMaterial = _technologyApp.GetFirstItem(t.Id);//主料
                technologyItem = _technologyApp.GetTechnologyItems(t.Id);//辅料
            }
            else
            {
                op = _orderProductApp.GetSingleOrderProductById(tId);//查找第一次
                if (op == null && w.ParentId != null)
                {
                    op = _orderProductApp.GetSingleOrderProductById(w.ParentId.Value);//查找第二次
                    if (op == null)
                    {
                        Worksheet tempw = _worksheetApp.GetSingleWorksheet(w.ParentId.Value);
                        if (tempw != null && tempw.ParentId != null && tempw.Type == 2)
                        {
                            op = _orderProductApp.GetSingleOrderProductById(tempw.ParentId.Value);//查找第三次
                        }
                    }
                }
                if (op != null)
                {
                    if (op.PrimaryID != null)
                    {
                        t = _technologyApp.GetSingleTechnologyById(op.PrimaryID.Value);
                    }
                    else
                    {
                        t = _technologyApp.GetSingleTechnologyById(op.Id);
                    }
                    firstMaterial = _technologyApp.GetFirstItem(t.Id);//主料
                    technologyItem = _technologyApp.GetTechnologyItems(t.Id);//辅料
                }
            }

            PrintDataView pdw = new PrintDataView();
            if (op != null)
            {
                decimal amount = w.StandardAmount;
                IEnumerable<Worksheet> subList = _worksheetApp.GetSubListTotal(tId);
                if (subList != null)
                {
                    foreach (var item in subList)
                    {
                        amount += item.WorkAmount;
                    }
                }
                w.WorkAmount = count;//op.Amount - amount;
                //重新计算给定长宽
                //decimal sizeWidth = sw;//p.SizeWidth.Value;
                //decimal sizeLenth = sl;//p.SizeLenth.Value;
                decimal chorg = ch == 0 ? 1 : ch;//t.Ch;
                decimal space = t.Space; //左右间距-mm
                decimal margin = t.Margin; //左右边距-mm
                decimal distance = t.Distance; //跳距-mm
                //var giveW = (sizeWidth * chorg + (chorg - 1) * space + margin * 2 + 15);//给定用料宽-mm
                //var comH = w.WorkAmount / chorg;
                //decimal giveH = 0;
                //if (t.WasteHReal == 0)
                //{
                //    giveH = ((sizeLenth + distance) * comH) / 1000; //给定用料长-m(米)
                //}
                //else
                //{
                //    giveH = ((sizeLenth + distance) * comH) * t.WasteHReal / 1000;//给定用料长-m(米)
                //}
                //t.GiveW = giveW;
                //t.GiveH = giveH;

                #region  储存每次打印数据

                Worksheet wback = _worksheetApp.GetSingleWorksheet(tId);
                List<TechnologyItemView> itemList = new List<TechnologyItemView>();

                pdw.ProductId = p.Id;
                pdw.ProductName = p.Name;
                pdw.SizeWidth = sw;
                pdw.SizeLenth = sl;
                //pdw.GiveW = giveW;
                //pdw.GiveH = giveH;
                pdw.WorkAmount = w.WorkAmount;
                pdw.FirstMaterial = firstMaterial.ProductName;
                //pdw.Tolerance = p.Tolerance;
                //pdw.ToleranceMinus = p.ToleranceMinus;
                pdw.Cv = cv;
                pdw.Ch = chorg;
                //pdw.Angel = p.Angel;
                //pdw.Color = p.Color;
                pdw.Distance = distance;
                pdw.WorkLenth = t.WorkLenth;
                pdw.Space = space;
                pdw.Margin = margin;
                //pdw.PackRequire = p.PackRequire;
                pdw.TechnologMemo = tMemo;
                pdw.EquipmentName = eqName;
                pdw.Dgren = dgpeople;
                pdw.OperationName = operatorModel.FamilyName;
                //pdw.Pack = p.Pack;//p.PackAmount;
                //pdw.PackAmount = p.PackAmount;//w.WorkAmount / (p.PackAmount == 0 ? 1 : p.PackAmount);
                foreach (var item in technologyItem)
                {
                    TechnologyItemView techItem = new TechnologyItemView();
                    techItem.ProductItemName = item.ProductName;
                    itemList.Add(techItem);
                }
                wback.PrintData = pdw.ToJson();
                _worksheetApp.Update(wback);
                #endregion
            }
            string newNumber = "";
            if (string.IsNullOrEmpty(w.Number))
            {
                #region 生成订单号

                string shortName = operatorModel.FamilyName;
                string shortTime = GenerateId.GenerateyyyyMm();
                //int lastWorksheet = _createNewNumberApp.GetLastWorksheetCount(shortName + "-" + shortTime, p.WorkType);
                int lastWorksheet = _createNewNumberApp.GetLastWorksheetCount(shortName + "-" + shortTime);
                /*int lastNum = 1;
                if (lastWorksheet != null && lastWorksheet.Number.Split('-').Length == 3 &&
                    Validate.IsIntByParse(lastWorksheet.Number.Split('-')[2]))
                {
                    int lastNum = Convert.ToInt32(lastWorksheet.Number.Split('-')[2]) + 1;
                }*/
                int lastNum = lastWorksheet + 1;
                newNumber = shortName + "-" + GenerateId.GenerateOrderNumberBack() + "-" +
                            lastNum.ToString().PadLeft(3, '0'); //生成采购编号

                #endregion
            }
            else
            {
                newNumber = w.Number;
            }

            w.TechnologMemo = tMemo;
            w.Number = newNumber;
            w.CreateTime = DateTime.Now;
            p.SizeWidth = sw;
            p.SizeLenth = sl;
            t.Ch = ch;
            t.Cv = cv;

            ViewBag.PrintDataView = pdw;
            ViewBag.ProductAccount = pac;
            ViewBag.Order = order;
            ViewBag.TechnologyItemList = technologyItem;
            ViewBag.FirstMaterial = firstMaterial;
            //ViewBag.Equipments = equipments;
            //ViewBag.TechType = techType;
            ViewBag.Product = p;
            ViewBag.Technology = t;
            ViewBag.OrderProduct = op;

            return View(w);
        }

        public ActionResult PrintWorksheetDataQj(Guid tId)
        {
            Worksheet w = _worksheetApp.GetSingleWorksheet(tId);
            PrintDataView pdw = null;
            Order order = null;
            if (w.OtherId != null)
            {
                order = _orderApp.GetInfo(w.OtherId.Value);
            }
            try
            {
                pdw = Common.Json.ToObject<PrintDataView>(w.PrintData);
            }
            catch (Exception ex)
            {
                pdw = null;
            }
            ViewBag.PrintDataView = pdw;
            ViewBag.Order = order;
            return View(w);
        }

        public ActionResult PrintWorksheetData(Guid tId)
        {
            Worksheet w = _worksheetApp.GetSingleWorksheet(tId);
            Product p = _technologyApp.GetSingleProduct(w.ProductId);
            //if (p.WorkType == 2)
            //{
            //    return RedirectToAction("PrintWorksheetDataQj", new { tId = tId });
            //}

            PrintDataView pdw = null;
            try
            {
                pdw = Common.Json.ToObject<PrintDataView>(w.PrintData);
            }
            catch (Exception ex)
            {
                pdw = null;
            }
            ViewBag.PrintDataView = pdw;
            return View(w);
        }
        /// <summary>
        /// 打印后去加工
        /// </summary>
        /// <param name="id"></param>
        /// <param name="number"></param>
        /// <param name="workCount">本次生产数量</param>
        /// <param name="productAccount">订货数量</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdateWorksheetStatus(Guid id, string number, decimal workCount, decimal productAccount)
        {
            Worksheet worksheet = _worksheetApp.GetSingleWorksheet(id);
            if (worksheet != null)
            {
                //打印分生产
                if (workCount < productAccount)
                {
                    Guid orgiGuidId = worksheet.Id; //初始Id
                    Worksheet w = _worksheetApp.GetSingleWorksheet(id);
                    w.Status = -1;
                    w.Number = number;
                    w.WorkAmount = w.WorkAmount + workCount;
                    _worksheetApp.Update(w); //原加工单不动

                    //修改OrderProduct工作进度
                    OrderProduct op = _orderProductApp.GetSingleOrderProductById(worksheet.Id);
                    if (op == null && w.ParentId != null)
                    {
                        op = _orderProductApp.GetSingleOrderProductById(w.ParentId.Value);
                    }
                    if (op != null)
                    {
                        op.Progress = 9;
                        _orderProductApp.Update(op);
                    }

                    //已生产的数量则另生个个加工单
                    Guid newGuidId = Guid.NewGuid();
                    worksheet.Id = newGuidId;
                    worksheet.Status = -101;
                    worksheet.Type = 2;
                    worksheet.ApplyTime = DateTime.Now;
                    worksheet.WorkAmount = workCount;
                    worksheet.ParentId = orgiGuidId;
                    worksheet.CreatorId = operatorModel.UserId;
                    worksheet.CreatorName = operatorModel.FamilyName;
                    //worksheet.CreateTime = nowTime;
                    _worksheetApp.Add(worksheet);

                    Relation re1 = new Relation();
                    re1.Id = Guid.NewGuid();
                    re1.TypeId = "Worksheet-Order";
                    re1.FirstId = newGuidId;
                    re1.SecondId = worksheet.OtherId;
                    _technologyApp.InsertRelation(re1);

                }
                else
                {
                    worksheet.Status = -101;
                    worksheet.Number = number;
                    worksheet.CreateTime = DateTime.Now;
                    worksheet.CreatorId = operatorModel.UserId;
                    worksheet.CreatorName = operatorModel.FamilyName;
                    _worksheetApp.Update(worksheet);
                }
            }
            return Result.ToJson();
        }

        public ActionResult GradeMaintenanceJg()
        {
            List<GradeMaintenance> gmList = _technologyApp.GetListGradeMaintenance(2);
            return View(gmList);
        }


        [HttpPost]
        [HandlerAjaxOnly]
        public string AddOrUpdateGradeMaintenance(GradeMaintenance gGradeMaintenance, string sign)
        {
            if (gGradeMaintenance.Data != null)
            {
                List<GradeMaintenance> gmList = Common.Json.ToObject<List<GradeMaintenance>>(gGradeMaintenance.Data);
                //修改
                if (sign == "1")
                {
                    foreach (var item in gmList)
                    {
                        GradeMaintenance web = _technologyApp.GetSingleGradeMaintenance(item.Id);
                        web.Num = item.Num;
                        _technologyApp.UpdateGradeMaintenance(web);
                    }
                }
                //添加
                if (sign == "-1")
                {
                    foreach (var item in gmList)
                    {
                        item.Id = Guid.NewGuid();
                        _technologyApp.InsertGradeMaintenance(item);
                    }
                    //_technologyApp.InsertGradeMaintenanceBatch(gmList);
                }
            }
            return Result.ToJson();
        }

    }
}